import { Component, OnInit } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { JsonApiService } from 'app/core/api/json-api.service'
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-outsource-processing-page',
  templateUrl: './outsource-processing-page.component.html',
  styleUrls: ['./outsource-processing-page.css']
})
export class OutsourceProcessingPageComponent implements OnInit {
  validatorOptions = {
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      deliveryDate: {
        validators: {
          notEmpty: {
            message: '请选择交货日期'
          },
          date: {
            format: 'YYYY-MM-DD',
            message: '请选择正确的时间,例如2018-01-01'
          }
        }
      },
      supplierName: {
        validators: {
          notEmpty: {
            message: '请输入供应商'
          }
        }
      }
    }
  }
  page: any = {
    supplierName: '', //供应商
    deliveryDate: '' //交货日期
  }

  page_title: string = '新增'
  pageType: string = 'new'
  curPage = 0 //页码缓存
  jumpData: any = {}

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
    activatedRoute.queryParams.subscribe(queryParams => {
    //   this.purchaseId = queryParams.id
    //   this.curPage = queryParams.nowPage
    //   this.pageType = queryParams.type
    //   if (common.getCookie('purchaseUpdata')) {
    //     this.jumpData = JSON.parse(common.getCookie('purchaseUpdata'))
    //     common.clearCookie('purchaseUpdata')
    //     this.page.buyApplyType = this.jumpData.buyApplyType
    //     this.page.deliveryDate = this.jumpData.deliveryDate
    //     this.page.applicant = this.jumpData.applicant
    //     this.page.applyDepartmet = this.jumpData.applyDepartmet
    //   }
    })
  }

  //表单校验
  onSubmit() {
    $('#purchaseForm').bootstrapValidator('validate') //开启验证
    const isValid = $('#purchaseForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.updata()
    }
  }
  //表单数据提交
  updata() {
    if (this.submitCheckTableData.length == 0) {
      this.jsonApiService.message('请上传委外加工申请明细')
      return
    }
    var url
    const data = {
      version: this.version,
      ...this.page
    }
    url = 'dtsConsignorExtraWorkApply/insertConsignorExtraWorkApply.html'
    const reqdata = 'data=' + JSON.stringify(data)
    this.jsonApiService.http(url, reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.router.navigate(['/supply-chain/outsource-processing-apply'], { queryParams: { nowPage: this.curPage } })
      }
    })
  }
  //返回资源列表页
  goBack() {
    this.router.navigate(['/supply-chain/outsource-processing-apply'], { queryParams: { nowPage: this.curPage } })
  }
  ngOnInit() {
    var that = this
    this.initDate().then(() => {
      if (this.pageType === 'updata') {
        this.page_title = '编辑'
        this.check_table_search()
      }
    })
  }
  // 删除输入
  delKey(type) {
    this.page[type] = ''
  }

  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              format: 'yyyy-mm-dd',
              language: 'zh-CN',
              autoclose: true,
              minView: 2
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.page.deliveryDate = time
              $('#purchaseForm').data('bootstrapValidator').resetForm()
            })
          resolve()
        })
      })
    })
  }
  cancelUploadUp(modal) {
    modal.hide()
  }
  viewUpload(modal) {
    modal.show()
  }

  //删除
  delSubmitCheck(row) {
    let msg, url
    msg = '此操作将删除临时数据,确认要删除？'
    url = 'dtsConsignorExtraWorkApply/deleteTempById.html'
    this.jsonApiService.confirm_message(msg).then(() => {
      const reqdata = 'id=' + row.id
      this.jsonApiService.http(url, reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.allSize = this.allSize - 1 //导入条数
          this.success = this.success - 1 // 成功条数
          this.check_table_search()
        }
      })
    })
  }

  //查询
  submitCheckTableData: any = [] //核对列表
  check_table_search() {
    let url, param
    param = {
      version: this.version
    }
    url = 'dtsConsignorExtraWorkApply/getTemplist.html'

    this.jsonApiService.http_obj(url, param).subscribe(result => {
      if (result.success) {
        this.submitCheckTableData = result.data
      }
    })
  }

  /**
   * 上传
   */
  fileUp: string = ''
  fileToUpload: File = null //上传文件回调参数
  // 显示导入弹框
  showImportModal(modal) {
    // 清空选择的文件
    modal.show()
    this.fileToUpload = null
  }
  //下载模板
  load_module() {
    var elemIF = document.createElement('iframe')
    elemIF.src = config.BaseURL + 'resources/template/consignorExtraWorkApply-Template.xlsx'
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  }
  // 关闭导入弹窗
  cancelUp(modal) {
    modal.hide()
    this.fileToUpload = null
  }
  clearFile() {
    this.fileUp = ''
  }
  //文件上传change回调
  fileChange(files: FileList) {
    this.fileToUpload = files.item(0)
    const isEXCEL =
      this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      this.fileToUpload.type === 'application/vnd.ms-excel'
    if (!isEXCEL) {
      this.jsonApiService.message('上传文件只能是 excel格式!')
      this.fileToUpload = null
      return
    }
  }
  allSize: any = '' //导入条数
  success: any = '' // 成功条数
  errMsg: any = [] //失败信息，是一个字符串数组
  version: string = '' // 导入版本号
  errSize: string = '' //失败条数
  isShowMsg: boolean = false
  //导入submit
  submitData(modal1) {
    let postParam = new FormData()
    postParam.append('file', this.fileToUpload)
    if (!this.fileToUpload) {
      this.jsonApiService.message('请上传文件')
      return false
    }
    this.jsonApiService.form_http('dtsConsignorExtraWorkApply/importExcelData.html', postParam).subscribe(data => {
      if (data.success) {
        modal1.hide()
        this.fileToUpload = null
        this.allSize = data.data.allSize //导入条数
        this.success = data.data.success // 成功条数
        this.errMsg = data.data.errMsg //失败信息，是一个字符串数组
        this.version = data.data.version // 导入版本号
        this.errSize = data.data.errSize //失败条数
        this.isShowMsg = true
        this.submitCheckTableData = []
        if (this.success != '' && this.success != 0) this.check_table_search()

        $('#purchaseForm').data('bootstrapValidator').resetForm()
      } else {
        this.isShowMsg = false
        this.fileToUpload = null
        $('#purchaseForm').data('bootstrapValidator').resetForm()
      }
    })
  }
}
